<template>
  <!-- 加入购物车弹窗 -->
  <van-popup
    v-model:show="props.show"
    position="bottom"
    :style="{ height: '60%' }"
    @close="handleClose"
  >
    <!-- 商品信息区域 -->
    <div class="goods-popup-header">
      <div class="goods-popup-img">
        <img :src="props.imgUrl" alt="商品封面" />
      </div>
      <div class="goods-price-wrap">
        <p class="goods-price">¥{{ props.price }}</p>
        <p class="spec-tip">请选择</p>
      </div>
    </div>

    <!-- 规格选择区域 -->
    <div class="goods-popup-content">
      <div
        class="popup-list"
        v-for="(item, index) in props.specificationList"
        :key="index"
      >
        <p class="spec-title">{{ item.name }}</p>
        <div class="spec-list">
          <button
            class="spec-btn"
            v-for="(value, valIndex) in item.valueList"
            :key="valIndex"
            :class="{ active: selectedSpec[item.name] === value }"
            @click="handleSpecSelect(item.name, value)"
          >
            {{ value.value }}
          </button>
        </div>
      </div>
    </div>

    <!-- 数量选择 + 操作按钮 -->
    <div class="popup-actions">
      <!-- 数量控制 -->
      <div class="quantity-control">
        <span class="quantity-label">购买数量</span>
        <div class="quantity-btn-group">
          <button class="quantity-btn" @click="handleQuantityChange(-1)">
            -
          </button>
          <input
            type="number"
            v-model.number="buyCount"
            class="quantity-input"
            min="1"
          />
          <button class="quantity-btn" @click="handleQuantityChange(1)">
            +
          </button>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="action-btns">
        <button class="cart-btn" @click="handleAddToCart">加入购物车</button>
        <button class="buy-btn" @click="handleBuyNow">立即购买</button>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";
import { showToast } from "vant";

// 定义接收的 Props
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  specificationList: {
    type: Array,
    default: () => [],
  },
  imgUrl: {
    type: String,
    default: "",
  },
  price: {
    type: Number,
    default: 0,
  },
  goodsInfo: {
    type: Object,
    default: () => ({}),
  },
  productList: {
    type: Array,
    default: () => [],
  },
});

// 定义事件 - 传递给父组件
const emit = defineEmits(["close", "addToCart", "buyNow"]);

// 响应式数据
const selectedSpec = ref({}); // 存储已选规格 { "规格1": "值1", "规格2": "值2" }
const buyCount = ref(1); // 购买数量

// 监听弹窗显示状态，重置选择
watch(
  () => props.show,
  (newVal) => {
    if (!newVal) {
      resetState();
    }
  }
);

/**
 * 处理规格选择
 * @param {string} specName 规格名称（如“规格”“颜色”）
 * @param {string} specValue 选中的规格值（如“1.5m床垫*1+枕头*2”“浅杏粉”）
 */
const handleSpecSelect = (specName, specValue) => {
  selectedSpec.value[specName] = specValue;
};

/**
 * 处理数量加减
 * @param {number} val 变化值（+1 或 -1）
 */
const handleQuantityChange = (val) => {
  buyCount.value += val;
  if (buyCount.value < 1) {
    buyCount.value = 1; // 数量最小为 1
  }
};

/**
 * 加入购物车逻辑
 * 1. 校验规格是否完整
 * 2. 拼接数据并传递给父组件
 */
const handleAddToCart = () => {
  if (!checkAllSpecSelected()) {
    showToast("请选择完整规格");
    return;
  }
  // 传递给父组件的数据
  const cartData = {
    goodsId: props.goodsInfo.id,
    number: buyCount.value,
    //根据规格筛选出对应的商品规格id
    productId: props.productList[0].id,
  };
  emit("addToCart", cartData);
  resetState(); // 重置状态
  //退出弹窗
  handleClose();
};

/**
 * 关闭弹窗逻辑
 */
const handleClose = () => {
  emit("close");
  resetState(); // 重置状态
};

/**
 * 校验是否所有规格都已选择
 * @returns {boolean} 是否完整选择
 */
const checkAllSpecSelected = () => {
  return props.specificationList.every((item) => {
    return selectedSpec.value[item.name] !== undefined;
  });
};

/**
 * 重置状态（关闭弹窗时调用）
 */
const resetState = () => {
  selectedSpec.value = {}; // 清空已选规格
  buyCount.value = 1; // 重置数量为 1
};
</script>

<style scoped lang="scss">
/* 弹窗整体样式 */
.van-popup {
  overflow-y: auto; // 内容超出可滚动
  padding: 16px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

/* 商品信息区域 */
.goods-popup-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .goods-popup-img {
    width: 340px;
    height: 340px;
    margin-right: 12px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 4px;
    }
  }

  .goods-price-wrap {
    display: flex;
    flex-direction: column;

    .goods-price {
      font-size: 38px;
      color: #f4333c; // 价格红色
      font-weight: bold;
      margin: 0;
    }

    .spec-tip {
      font-size: 28px;
      color: #999;
      margin: 4px 0 0;
    }
  }
}

/* 规格选择区域 */
.goods-popup-content {
  margin-bottom: 36px;

  .popup-list {
    margin-bottom: 16px;

    .spec-title {
      font-size: 34px;
      font-weight: bold;
      color: #333;
      margin-bottom: 20px;
    }

    .spec-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .spec-btn {
        padding: 12px 18px;
        border: 1px solid #dcdcdc;
        border-radius: 20px;
        background-color: #6464642c;
        cursor: pointer;
        transition: all 0.2s;

        &.active {
          background-color: #f4333c;
          color: #fff;
          border-color: #f4333c;
        }

        &:hover {
          border-color: #f4333c;
        }
      }
    }
  }
}

/* 数量控制 + 操作按钮 */
.popup-actions {
  flex: 1;
  border-top: 1px solid #f5f5f5;
  padding-top: 16px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;

  // 数量控制
  .quantity-control {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 36px;

    .quantity-label {
      font-size: 36px;
      color: #333;
    }

    .quantity-btn-group {
      display: flex;
      align-items: center;

      .quantity-btn {
        width: 60px;
        height: 60px;
        line-height: 60px;
        text-align: center;
        border: 1px solid #dcdcdc;
        background-color: #fff;
        cursor: pointer;
        font-size: 30px;
        transition: all 0.2s;

        &:hover {
          border-color: #f4333c;
          color: #f4333c;
        }
      }

      .quantity-input {
        width: 70px;
        height: 58px;
        text-align: center;
        border: 1px solid #dcdcdc;
        border-left: none;
        border-right: none;
        padding: 0;
        margin: 0;
      }
    }
  }

  /* 操作按钮容器 */
  .action-btns {
    display: flex; /* 横向排列 */
    width: 100%; /* 填满父容器 */
  }

  /* 通用按钮样式 */
  .cart-btn,
  .buy-btn {
    flex: 1; /* 平分宽度 */
    height: 70px; /* 按钮高度 */
    display: flex; /* 开启flex布局 */
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    color: #fff; /* 文字颜色 */
    font-size: 36px; /* 调整字体大小（根据设计图微调） */
    cursor: pointer; /* 鼠标手势 */
    transition: all 0.2s; /* 过渡动画 */
  }

  /* 加入购物车按钮 */
  .cart-btn {
    background: linear-gradient(to right, #ffd166, #ff8c00); /* 黄→橙渐变 */
    border-top-left-radius: 50px; /* 左上角圆角 */
    border-bottom-left-radius: 50px; /* 左下角圆角 */
    border: none
  }

  /* 立即购买按钮 */
  .buy-btn {
    background: linear-gradient(to right, #ff4b4b, #f4333c); /* 浅红→深红渐变 */
    border-top-right-radius: 50px; /* 右上角圆角 */
    border-bottom-right-radius: 50px; /* 右下角圆角 */
    border: none
  }

  /*  hover 效果 */
  .cart-btn:hover,
  .buy-btn:hover {
    opacity: 0.9; /* 透明度降低，增强交互反馈 */
  }
}
</style>
